import React, { Suspense } from 'react';
import { Spin } from 'antd';
import { getRouteConfig } from './routeConfig.js';

// 加载中的组件
const LoadingComponent = () => (
  <div style={{ 
    display: 'flex', 
    justifyContent: 'center', 
    alignItems: 'center', 
    height: '400px' 
  }}>
    <Spin size="large" />
  </div>
);

// 错误边界组件
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  componentDidCatch(error, errorInfo) {
    console.error('动态组件加载失败:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div style={{ 
          display: 'flex', 
          flexDirection: 'column',
          justifyContent: 'center', 
          alignItems: 'center', 
          height: '400px',
          color: '#ff4d4f'
        }}>
          <h3>页面加载失败</h3>
          <p>请刷新页面重试</p>
          <button 
            onClick={() => window.location.reload()}
            style={{
              padding: '8px 14px',
              backgroundColor: '#1890ff',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer'
            }}
          >
            刷新页面
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

// 动态组件加载器
const DynamicComponentLoader = ({ path, ...props }) => {
  const routeConfig = getRouteConfig(path);
  
  if (!routeConfig) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '400px',
        color: '#999'
      }}>
        <div>
          <h3>页面未找到</h3>
          <p>路径: {path}</p>
        </div>
      </div>
    );
  }

  const Component = routeConfig.component;

  return (
    <ErrorBoundary>
      <Suspense fallback={<LoadingComponent />}>
        <Component {...props} />
      </Suspense>
    </ErrorBoundary>
  );
};

export default DynamicComponentLoader; 